from starlette.endpoints import HTTPEndpoint
from starlette.responses import JSONResponse
from database import Session
from sqlalchemy.exc import DBAPIError
import logging
import config
from model.ModPowerSupplyBureauOperator import PowerSupplyBureauOperator as psbo, bureauOperatorSchema
from dao import DaoPowerSupplyBureauOperator
import pendulum
import requests
import json
from redis_connection import redis_conn as redis
from wxpublic import wx_public_message

class PowerSupplyBureauOperator(HTTPEndpoint):

    async def get(self, request):
        session = Session()
        try:
            openid = request.query_params["openid"]
            return DaoPowerSupplyBureauOperator.get_operator_info(session, openid)
        finally:
            session.close()


class AllPowerSupplyBureauOperator(HTTPEndpoint):

    def __init__(self, scope):
        super().__init__(scope)
        self._logger = logging.getLogger(type(self).__name__)

    async def get(self, request):
        session = Session()
        try:
            users = session.query(psbo).order_by(psbo.power_supply_bureau.asc()).all()
            session.rollback()
            return JSONResponse(bureauOperatorSchema.dump(users, many=True).data)
        except (DBAPIError, ValueError) as err:
            session.rollback()
            self._logger.info(err.message)
            return JSONResponse({}, status_code=404)
        finally:
            session.close()


class LinkPowerSupplyBureauOperator(HTTPEndpoint):

    def __init__(self, scope):
        super().__init__(scope)
        self._logger = logging.getLogger(type(self).__name__)

    async def get(self, request):
        session = Session()
        try:
            target_user_id = request.path_params['openid']
            users = session.query(psbo).filter(psbo.openid == target_user_id).one()
            session.rollback()
            return JSONResponse(bureauOperatorSchema.dump(users).data)
        except (DBAPIError, ValueError) as err:
            self._logger.info(err.message)
            return JSONResponse({}, status_code=404)
        finally:
            session.close()

    async def put(self, request):
        session = Session()
        try:
            target_user_id = request.path_params['openid']
            links = await request.json()
            target_user = session.query(psbo).filter(psbo.openid == target_user_id).one()
            target_user.power_supply_bureau = links['belongs']
            target_user.supervision_department = links['supervision']
            target_user.remark = links['remark']
            target_user.stationid = links['stationid']
            if links['jointime'] is None:
                target_user.jointime = pendulum.now()
            session.commit()

            #发送客服消息
            msg = "您好，我公司业务经理已经为您开通了客服平台的操作权限，您可以查阅报告信息了。"
            wx_public_message.send_to_user(target_user_id, msg)
            return JSONResponse({"result": "1"})
            # 发送模板信息
            #from wxpublic.wx_public_message import send_template_message
            #from model.ModPowerSupplyBureauList import PowerSupplyBureauList
            #from collections import defaultdict
            #levels = defaultdict(
            #   lambda: "未定义职务",
            #   {
            #      "1": "班长(专工)",
            #      "2": "主任",
            #       "3": "经理",
            #       "9": "供电所人员"
            #   }
            #)
            #belongs_area = session.query(PowerSupplyBureauList)\
            #  .filter(PowerSupplyBureauList.id == links["belongs"])\
            #   .first()
            #send_template_message(target_user_id,
            #                  config.TEMPLATE_AUTHORIZE,
            #                   {
            #                      "first": {
            #                            "value": f"您好，我公司业务经理已经为您开通了客服平台的操作权限。",
            #                            "color": "#000000"
            #                        },
            #                        "keyword1": {
            #                            "value": belongs_area.name,
            #                          "color": "#1736c0"
            #                      },
            #                        "keyword2": {
            #                            "value": levels[links['supervision']],
            #                            "color": "#1736c0"
            #                        },
            #                       "remark": {
            #                           "value": "您现在可以查阅报告信息了。",
            #                           "color": "#000000"
            #                       }
            #                   })

        except (DBAPIError, ValueError) as err:
            session.rollback()
            self._logger.info(err.message)
            return JSONResponse({"result": "0"})
        finally:
            session.close()
